package output;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;


import task.AbstractTaskRunner;

import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;

public class OutputSQLite {
	
	private static OutputSQLite instance = null;

	
	public static OutputSQLite getInstance() {
		if(instance == null) {
			instance = new OutputSQLite();
		}
		return instance;
	}
	
	private SQLiteConnection db = null;
	
	private String sql = "insert into result " +
			"(time, behavior, wstype, wssize, etype, stride, threadnum, mstrategy, mtimes, host, cost) " +
			"values (datetime('now'), '%s', '%s', %d, '%s', %d, %d, '%s', %d, '%s', %s)";

	private String hostName = "";
	
	private OutputSQLite() {
		try {
			Process p = Runtime.getRuntime().exec("uname -a");
			BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			this.hostName = br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void init(File dbFile) {
		if(!dbFile.exists()) {
			System.out.println("db file not exist.");
		}
		try {
			db = new SQLiteConnection(dbFile);
			db.open(true);
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public void cleanup() {
		db.dispose();
	}
	
	public void outputTaskResult(AbstractTaskRunner taskRunner) {
		try {
			db.exec(String.format(sql, 
					taskRunner.getTask().getBehavior(), 
					taskRunner.getTask().getWorkingsetType(), 
					taskRunner.getTask().getWorkingsetSize(), 
					taskRunner.getTask().getElementType(), 
					taskRunner.getTask().getStride(), 
					taskRunner.getTask().getThreadNum(), 
					taskRunner.getMeasureStrategy(), 
					taskRunner.getMeasureTime(), 
					this.hostName, 
					taskRunner.getTaskTimeConsuming()));
//			SQLiteStatement statement = db.prepare(String.format(sql, 
//					taskRunner.getTask().getBehavior(), 
//					taskRunner.getTask().getWorkingsetType(), 
//					taskRunner.getTask().getWorkingsetSize(), 
//					taskRunner.getTask().getElementType(), 
//					taskRunner.getTask().getStride(), 
//					taskRunner.getTask().getThreadNum(), 
//					taskRunner.getMeasureStrategy(), 
//					taskRunner.getMeasureTime(), 
//					this.hostName, 
//					taskRunner.getTaskTimeConsuming()));
//			statement.
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
